package com.jpyl.jpMedicalTreatment.view.activity.home;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;

import com.cjj.MaterialRefreshLayout;
import com.cjj.MaterialRefreshListener;
import com.jpyl.jpMedicalTreatment.R;
import com.jpyl.jpMedicalTreatment.common.MedicalSettings;
import com.jpyl.jpMedicalTreatment.model.AgentMessageModel;
import com.jpyl.jpMedicalTreatment.model.ErrorMessageModel;
import com.jpyl.jpMedicalTreatment.model.PopwindowModel;
import com.jpyl.jpMedicalTreatment.model.ResponseModel;
import com.jpyl.jpMedicalTreatment.model.RxSpf_UserModel;
import com.jpyl.jpMedicalTreatment.network.Network;
import com.jpyl.jpMedicalTreatment.network.api.ApiError;
import com.jpyl.jpMedicalTreatment.network.api.RequestApi;
import com.jpyl.jpMedicalTreatment.view.activity.BaseActivity;
import com.jpyl.jpMedicalTreatment.view.adapter.MyDoctorsAdapter;
import com.jpyl.jpMedicalTreatment.view.widget.sortlistview.MyPopupwindow;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 我的医生（代理可见）
 * Created by 15697 on 2019/3/8.
 */

public class MyDoctorActivity extends BaseActivity {
    @BindView(R.id.rv_refresh_layout)
    RecyclerView rvRefreshLayout;
    @BindView(R.id.mr_refresh_layout)
    MaterialRefreshLayout mrRefreshLayout;
    @BindView(R.id.tv_refreshLayout_Empty)
    TextView tvRefreshLayoutEmpty;

    MyDoctorsAdapter adapter;
    MyPopupwindow popSituation; //出货情况/检查情况；（三种检查结果）
    List<PopwindowModel> list_popSituation = new ArrayList<>();  //出货情况，检查情况
    final RequestApi publicApi = Network.getRequestApi();
    RxSpf_UserModel spfUserModel;
    String userId = "";
    List<AgentMessageModel> list = new ArrayList<>();

    @Override
    protected int getLayoutId() {
        return R.layout.activity_refrsh_layout;
    }

    @Override
    public void afterCreate(Bundle savedInstanceState) {
        spfUserModel = RxSpf_UserModel.create(this);
        userId = spfUserModel.userId().get();
        if (getIntent().getIntExtra(MedicalSettings.STRUSERTYPE, -1) == MedicalSettings
                .USERTYPE_AGENT) {
            //代理
            list_popSituation = MedicalSettings.getDocSituation();
        } else {
            //总代理
            list_popSituation = MedicalSettings.getGeneralAgentSituation();
        }

        mTitleTv.setText(getString(R.string.cer_myDoctor));
        adapter = new MyDoctorsAdapter(this, list);
        rvRefreshLayout.setAdapter(adapter);
        rvRefreshLayout.setLayoutManager(new GridLayoutManager(this, 1));
        mrRefreshLayout.setLoadMore(false);
        mrRefreshLayout.setMaterialRefreshListener(new MaterialRefreshListener() {
            @Override
            public void onRefresh(MaterialRefreshLayout materialRefreshLayout) {
                jpylQueryMyDoctorByName();
            }

            @Override
            public void onRefreshLoadMore(MaterialRefreshLayout materialRefreshLayout) {
                super.onRefreshLoadMore(materialRefreshLayout);
                materialRefreshLayout.finishRefreshLoadMore();

            }
        });

        adapter.setItemClickListener(new MyDoctorsAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(final int position) {
                popSituation = new MyPopupwindow(MyDoctorActivity.this, list_popSituation);
                popSituation.show();
                popSituation.setCallBack(new MyPopupwindow.MyPopwindowListener() {
                    @Override
                    public void selectPositon(int i) {
                        if (list_popSituation.get(i).value == MedicalSettings.SITUATION_1) {
                            //出货情况
                            popSituation.dismiss();
                            startActivity(new Intent(getApplicationContext(),
                                    OutSituationActivity.class).putExtra("list", list.get(i))
                                    .putExtra("flag", "2"));
                        } else {
                            //我的患者
                            popSituation.dismiss();
                            startActivity(new Intent(getApplicationContext(),
                                    PatientListActivity.class).putExtra("isDoctor", true)
                                    .putExtra("userId", list.get(position).getId()).putExtra
                                            ("flag", "3"));
                        }
                    }
                });
            }
        });
        jpylQueryMyDoctorByName();
    }

    private void jpylQueryMyDoctorByName() {
        String userid = spfUserModel.userId().get();
        publicApi.jpylQueryMyDoctorByName(userid, "").map(new Func1<ResponseModel<List<AgentMessageModel>>, List<AgentMessageModel>>() {
            @Override
            public List<AgentMessageModel> call(ResponseModel<List<AgentMessageModel>>
                                                        responseModel) {
                if (responseModel.getCode() != 0) {
                    ErrorMessageModel messageModel = new ErrorMessageModel(responseModel.getMsg());
                    throw new ApiError(messageModel);
                }
                return responseModel.getData();
            }
        })
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<List<AgentMessageModel>>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        mrRefreshLayout.finishRefreshing();
                        mrRefreshLayout.finishRefresh();
                        e.printStackTrace();
                        if (e instanceof ApiError) {
                            ApiError error = (ApiError) e;
                        } else {
                        }
                    }

                    @Override
                    public void onNext(List<AgentMessageModel> lists) {
                        mrRefreshLayout.finishRefreshing();
                        mrRefreshLayout.finishRefresh();
                        list.clear();
                        list.addAll(lists);
                        adapter.notifyDataSetChanged();
                    }
                });
    }
}
